package com.softeem.iov.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.softeem.iov.dto.R;
import com.softeem.iov.entity.Brand;
import com.softeem.iov.service.IBrandService;
import com.softeem.iov.utils.QiniuOssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 车辆品牌表 前端控制器
 * </p>
 *
 * @author softeem
 * @since 2023-09-19
 */
@CrossOrigin  //设置允许跨域请求
@RestController
@RequestMapping("/iov/brand")
public class BrandController {

    @Autowired
    private IBrandService brandService;

    @Autowired
    private QiniuOssUtils qiniuOssUtils;

    /**
     * 品牌新增(含文件上传)
     * @param brand
     * @return
     */
    @PostMapping("/add")
    public R add(@Valid Brand brand, MultipartFile imgLogo) throws IOException {
        //获取上传文件的输入流
        InputStream in = imgLogo.getInputStream();
        //获取上传文件文件名称（key）
        String fname = imgLogo.getOriginalFilename();
        //对上传文件的文件名重命名（防止文件名重复，而产生文件覆盖问题）
        //随机生成UUID
        String name = IdUtil.simpleUUID();
        //获取源文件的后缀名
        String suffix = FileNameUtil.getSuffix(fname);
        //对文件重命名
        fname = name + "." + suffix;
        //上传文件到七牛云
        String logo = qiniuOssUtils.upload(in, fname);
        //设置返回的文件地址到对象
        brand.setLogo(logo);
        //执行添加逻辑
        return brandService.add(brand);
    }

    /**
     * 品牌分页查询
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
        return brandService.list(page,limit);
    }

    /**
     * 品牌修改
     * @param brand
     * @return
     */
    @PutMapping("/update")
    public R update(Brand brand){
        return brandService.update(brand);
    }

    /**
     * 删除品牌
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public R remove(@PathVariable @Pattern(regexp = "\\d+",message = "id必须为数值") Integer id){
        return brandService.removeById(id);
    }
}
